﻿using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class refunds : System.Web.UI.Page
{
    private readonly string mCurrentModule = Credits.Module.ID;
    private readonly string mPageName = "Carte de credit";
    private string appPath = string.Empty;
       
    protected void Page_Load(object sender, EventArgs e)
    {
        appPath = Utils.GetApplicationPath(Request);
        Utils.GetMaster(this).PerformPreloadActions(mCurrentModule, mPageName);

        bool allowHere = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoans.Name, Constants.Constants.Classifiers.Permissions_View);
        if (allowHere)
        {
            if (!IsPostBack)
            {
                ShowPanel(previewPanel.ID);
            }
        }
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels

        previewPanel.Visible = false;
        emptyPanel.Visible = false;

        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "previewPanel":
                    previewPanel.Visible = true;
                    FillPreviewForm();
                    break;
             
                case "emptyPanel":
                    emptyPanel.Visible = true;
                    break;

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    protected void ClearPreviewForm()
    {
        dateNowLabel.Text = string.Empty; 
        clientNameLabel.Text = string.Empty;
        loanNrLabel.Text = string.Empty;
        loanInitialChangeRateLabel.Text = string.Empty;
        loanRealChangeRate.Text = string.Empty;

        refundsLoanGridView.DataSource = null;
        refundsLoanGridView.DataBind();
    }

    protected void FillPreviewForm()
    {
        try
        {        
            ClearPreviewForm();
            dateNowLabel.Text = DateTime.Now.ToString(Constants.Constants.ISODateBackwardDotsFormat);

            int loanID = 0;
            int.TryParse(Request["loanID"], out loanID);

            if (loanID != 0)
            {
                Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(loanID);
                if (loanInfo != null)
                {
                    clientNameLabel.Text = loanInfo.ClientFirstLastName;
                    loanNrLabel.Text = loanInfo.ContractCode.ToString();
                    sumLoanLabel.Text = loanInfo.ContractAmountInLei.ToString();                    
                    changeRateHiddenField.Value = loanInfo.CurrencyID.ToString();

                    if (loanInfo.CurrencyID != 0 && loanInfo.CurrencyID != (int)Constants.Constants.CurrencyList.MDL)
                    {
                        decimal initialChangeRate = loanInfo.CurrencyChangeRate;
                        decimal realChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(DateTime.Now.Date, loanInfo.CurrencyID);

                        string currencyChange = loanInfo.CurrencyChangeRate.ToString();
                        if (string.IsNullOrEmpty(currencyChange))
                        {
                            currencyChange = "1";
                        }
                        loanInitialChangeRateLabel.Text = currencyChange;

                        loanRealChangeRate.Text = realChangeRate.ToString();

                        if (initialChangeRate < realChangeRate)
                        {
                            Utils.ModuleCredits().ApplyNewChangeRateForloanOrders(loanID, realChangeRate, DateTime.Now.Date);
                        }
                    }
                    else
                    {
                        string currencyChange = loanInfo.CurrencyChangeRate.ToString();
                        if (string.IsNullOrEmpty(currencyChange))
                        {
                            currencyChange = "1";
                        }
                        loanInitialChangeRateLabel.Text = currencyChange;
                    }
                    

                    DataTable loanOrders = Utils.ModuleCredits().GetRefundsLoanOrderList(loanID);
                    if (loanOrders != null)
                    {
                        for (int index = 0; index < loanOrders.Rows.Count; index++)
                        {
                            bool isFinis = false;
                            string finisValue = loanOrders.Rows[index][13].ToString();
                            if (finisValue.Equals("1"))
                            {
                                isFinis = true;
                            }
                           
                            if (isFinis == false)
                            {
                                string iterationValue = loanOrders.Rows[index][1].ToString();
                                int iterationID = 0;
                                int.TryParse(iterationValue, out iterationID);
                                DataRow[] selectedRows = loanOrders.Select(" toogleID ='-' AND iterationID = " + iterationID);
                                if(selectedRows!=null && selectedRows.Length>0)
                                {
                                    finisValue = selectedRows[0][13].ToString();
                                    if (finisValue.Equals("1"))
                                    {
                                        isFinis = true;
                                    }
                                    loanOrders.Rows[index][13] = isFinis;
                                }
                            }

                        }
                    }

                    refundsLoanGridView.DataSource = loanOrders;
                    refundsLoanGridView.DataBind();


                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    #region initierea variabilelor
    decimal sumRateAmountForFooter = 0;
    decimal sumRatePaysForFooter = 0;
    decimal sumRateDiffForFooter = 0;

    decimal sumPercentAmountForFooter = 0;
    decimal sumPercentPaysForFooter = 0;
    decimal sumPercentDiffForFooter = 0;

    decimal sumPenaltyForFooter = 0;
    decimal sumPenaltyPaysForFooter = 0;
    decimal sumPenaltyDiffForFooter = 0;
    
    decimal sumCorrentionAmountForFooter = 0;
    decimal sumCorrectionPaysForFooter = 0;
    decimal sumCorrectionDiffForFooter = 0;

    decimal sumCommissionForFooter = 0;
    decimal sumCommissionPaysForFooter = 0;
    decimal sumCommissionDiffForFooter = 0;

    decimal sumTotalAmountForFooter = 0;
    decimal sumTotalPaysForFooter = 0;
    decimal sumTotalDiffForFooter = 0;

    #endregion

    DateTime curretDate = DateTime.Now;

    protected void refundsLoanGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        try
        {           
            int countRow = 0;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable gridTable = (DataTable)refundsLoanGridView.DataSource;
                countRow = e.Row.RowIndex;
                e.Row.Attributes["id"] = countRow.ToString();
                for (int i = 0; i < e.Row.Cells.Count-1; i++)
                {
                    if (i == 0)
                    {
                        string togleValue = string.Empty;
                        togleValue = e.Row.Cells[i].Text;
                        if (!String.IsNullOrEmpty(togleValue) && togleValue.Equals("-"))
                        {
                            e.Row.Cells[i].Attributes["onclick"] = string.Format("toggleRow(this.id)");
                            e.Row.Cells[i].Attributes["id"] = string.Format("td" + countRow.ToString());
                            
                            string iterationValue = gridTable.Rows[e.Row.RowIndex][1].ToString();
                            string isFinis = gridTable.Rows[e.Row.RowIndex][13].ToString();

                            DataRow[] selectedRow = gridTable.Select("iterationID = " + iterationValue);
                            if (selectedRow != null)
                            {
                                if (selectedRow.Length > 1)
                                {
                                    e.Row.Cells[i].Text = string.Format("+");
                                    if (isFinis.Equals(string.Format("1")))
                                    {
                                        e.Row.Attributes["class"] = string.Format("parentRowPlus");
                                    }
                                    else
                                    {
                                        e.Row.Attributes["class"] = string.Format("parentRowMinus");
                                    }
                                }
                                else
                                {
                                    e.Row.Attributes["class"] = string.Format("parentRowMinus");
                                }
                            }
                        }
                        else
                        {
                            e.Row.Attributes["style"] = string.Format("display: none;");
                        }
                    }
                    else
                    {
                        e.Row.Cells[i].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.refundsLoanGridView, "Select$" + e.Row.RowIndex);
                    }
                }

                string paysLabel = e.Row.Cells[2].Text;
                if (paysLabel != null)
                {
                    int paysValue = 0;
                    int.TryParse(paysLabel, out paysValue);

                    Label rateAmountLabel = (Label)e.Row.FindControl("rateAmountLabel");
                    Label percentAmountLabel = (Label)e.Row.FindControl("percentAmountLabel");
                    Label penaltyLabel = (Label)e.Row.FindControl("penaltyLabel");
                    Label rateCorrectionLabel = (Label)e.Row.FindControl("rateCorrectionLabel");
                    Label commissionLabel = (Label)e.Row.FindControl("commissionAdmLabel");
                    Label totalAmountLabel = (Label)e.Row.FindControl("totalAmountLabel");
                                  
                    if (paysValue > 0)
                    {
                        #region rateAmount
                        if (rateAmountLabel != null)
                        {
                            decimal tempRate = 0;
                            decimal.TryParse(rateAmountLabel.Text, out tempRate);
                            sumRatePaysForFooter += tempRate;
                        }
                        #endregion
                        #region percent
                        if (percentAmountLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(percentAmountLabel.Text, out tempVal);
                            sumPercentPaysForFooter += tempVal;
                        }
                        #endregion
                        #region penalty
                        if (penaltyLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(penaltyLabel.Text, out tempVal);
                            sumPenaltyPaysForFooter += tempVal;
                        }
                        #endregion
                        #region correction
                        if (rateCorrectionLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(rateCorrectionLabel.Text, out tempVal);
                            sumCorrectionPaysForFooter += tempVal;
                        }
                        #endregion
                        #region commission
                        if (commissionLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(commissionLabel.Text, out tempVal);
                            sumCommissionPaysForFooter+= tempVal;
                        }
                        #endregion
                        #region totalTotal
                        if (totalAmountLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(totalAmountLabel.Text, out tempVal);
                            sumTotalPaysForFooter += tempVal;
                        }  
                        #endregion
                    }
                    else
                    {
                        #region rateAmount
                        if (rateAmountLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(rateAmountLabel.Text, out tempVal);
                            sumRateAmountForFooter += tempVal;
                        }
                        #endregion
                        #region percent
                        if (percentAmountLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(percentAmountLabel.Text, out tempVal);
                            sumPercentAmountForFooter += tempVal;
                        }
                        #endregion
                        #region penalty
                        if (penaltyLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(penaltyLabel.Text, out tempVal);
                            sumPenaltyForFooter += tempVal;
                        }
                        #endregion
                        #region correction
                        if (rateCorrectionLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(rateCorrectionLabel.Text, out tempVal);
                            sumCorrentionAmountForFooter += tempVal;
                        }
                        #endregion
                        #region commission
                        if (commissionLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(commissionLabel.Text, out tempVal);
                            sumCommissionForFooter += tempVal;
                        }
                        #endregion
                        #region totalTotal
                        if (totalAmountLabel != null)
                        {
                            decimal tempVal = 0;
                            decimal.TryParse(totalAmountLabel.Text, out tempVal);
                            sumTotalAmountForFooter += tempVal;
                        }  
                        #endregion
                    }
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
            #region totalRate
                            Label totalRateAmountLabel = (Label)e.Row.FindControl("totalRateAmountLabel");
                            totalRateAmountLabel.Text = sumRateAmountForFooter.ToString();

                            Label totalRatePaysLabel = (Label)e.Row.FindControl("totalRatePaysLabel");
                            totalRatePaysLabel.Text = sumRatePaysForFooter.ToString();

                            Label totalRateDiffLabel = (Label)e.Row.FindControl("totalRateDiffLabel");
                            totalRateDiffLabel.Text = (sumRateAmountForFooter - sumRatePaysForFooter).ToString();
            #endregion

            #region totalPercent
                            Label totalPercentAmountLabel = (Label)e.Row.FindControl("totalPercentAmountLabel");
                            totalPercentAmountLabel.Text = sumPercentAmountForFooter.ToString();

                            Label totalPercentPaysLabel = (Label)e.Row.FindControl("totalPercentPaysLabel");
                            totalPercentPaysLabel.Text = sumPercentPaysForFooter.ToString();

                            Label totalPercentDiffLabel = (Label)e.Row.FindControl("totalPercentDiffLabel");
                            totalPercentDiffLabel.Text = (sumPercentAmountForFooter - sumPercentPaysForFooter).ToString();
            #endregion

            #region totalPenalty
                            Label totalPenaltyLabel = (Label)e.Row.FindControl("totalPenaltyLabel");
                            totalPenaltyLabel.Text = sumPenaltyForFooter.ToString();

                            Label totalPenaltyPaysLabel = (Label)e.Row.FindControl("totalPenaltyPaysLabel");
                            totalPenaltyPaysLabel.Text = sumPenaltyPaysForFooter.ToString();

                            Label totalPenaltyDiffLabel = (Label)e.Row.FindControl("totalPenaltyDiffLabel");
                            totalPenaltyDiffLabel.Text = (sumPenaltyForFooter - sumPenaltyPaysForFooter).ToString();
            #endregion

            #region totalRateCorrection
                            Label totalRateCorrectionLabel = (Label)e.Row.FindControl("totalRateCorrectionLabel");
                            totalRateCorrectionLabel.Text = sumCorrentionAmountForFooter.ToString();

                            Label totalRateCorrectionPaysLabel = (Label)e.Row.FindControl("totalRateCorrectionPaysLabel");
                            totalRateCorrectionPaysLabel.Text = sumCorrectionPaysForFooter.ToString();

                            Label totalRateCorrectionDiffLabel = (Label)e.Row.FindControl("totalRateCorrectionDiffLabel");
                            totalRateCorrectionDiffLabel.Text = (sumCorrentionAmountForFooter - sumCorrectionPaysForFooter).ToString();
            #endregion

            #region totalCommission
                            Label totalCommissionAdmLabel = (Label)e.Row.FindControl("totalCommissionAdmLabel");
                            totalCommissionAdmLabel.Text = sumCommissionForFooter.ToString();

                            Label totalCommissionPaysLabel = (Label)e.Row.FindControl("totalCommissionPaysLabel");
                            totalCommissionPaysLabel.Text = sumCommissionPaysForFooter.ToString();

                            Label totalCommissionDiffLabel = (Label)e.Row.FindControl("totalCommissionDiffLabel");
                            totalCommissionDiffLabel.Text = (sumCommissionForFooter - sumCommissionPaysForFooter).ToString();
            #endregion

            #region totalTotal
                            Label totalTotalAmountLabel = (Label)e.Row.FindControl("totalTotalAmountLabel");
                            totalTotalAmountLabel.Text = sumTotalAmountForFooter.ToString();

                            Label totalTotalPaysLabel = (Label)e.Row.FindControl("totalTotalPaysLabel");
                            totalTotalPaysLabel.Text = sumTotalPaysForFooter.ToString();

                            Label totalTotalDiffLabel = (Label)e.Row.FindControl("totalTotalDiffLabel");
                            totalTotalDiffLabel.Text = (sumTotalAmountForFooter-sumTotalPaysForFooter).ToString();
            #endregion
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    protected void refundsLoanGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (refundsLoanGridView.SelectedRow != null)
        {
            GridViewRow row = refundsLoanGridView.SelectedRow;
            string text = row.Cells[1].Text;

            int loanID = 0;
            int.TryParse(Request["loanID"], out loanID);

            int iterationID = 0;
            int.TryParse(text, out iterationID);

            int paysID = 0;
            int.TryParse(row.Cells[2].Text, out paysID);

            decimal currenty = 0;
            decimal.TryParse(row.Cells[10].Text, out currenty);

            if (loanID != 0)
            {
                refundPaysControl.LoanID = loanID;
                refundPaysControl.IterationID = iterationID;
                refundPaysControl.PayID = paysID;
                refundPaysControl.CurrencyID = int.Parse(changeRateHiddenField.Value);
                refundPaysControl.CurrencyChangeRate = decimal.Parse(loanInitialChangeRateLabel.Text);
                refundPaysControl.Currenty = currenty;

                refundPaysControl.Show();                                
            }
        }
        else
        {
            Utils.InfoText(this, "Atentie!", "Nu s-a selectat iteratia.");
        }
    }

    protected void RefundsSelecetd_Event(object sender, Controls_RefundPays.RefundsWindowEventsArg e)
    {
        ShowPanel(previewPanel.ID);
    }
    protected void mifosID_Click(object sender, EventArgs e)
    {
        string linkRedirect = "MRefunds.aspx?loanID=" + Request["loanID"];
        Response.Redirect(linkRedirect);
    }
}